package suanfa;

public class BS_Test1 {

    public static void main(String[] args) {
        int[] arr = new int[]{3, 5, 10, 11, 45};
        int index = bsFind(arr, 10);
        if (index > -1) {
            System.out.println("位置：" + index);
        } else {
            System.out.println("未找到数据");
        }
    }

    private static int bsFind(int[] arr, int num) {
        int L = 0, R = arr.length - 1;
        int findIdx = -1;
        while (findIdx == -1) {
            int idx = (L + R) / 2;
            if (arr[idx] == num) {
                findIdx = idx;
            } else if (arr[idx] > num) {
                R = idx - 1;
            } else {
                L = idx + 1;
            }
            //当出现R位置比L位置还小或等于L位置时
            //则已经搜索完成也没找到数据
            if (R < L) {
                break;
            }
        }
        return findIdx;
    }
}
